
package cn.springmix.base.lang.exception;


import cn.springmix.base.lang.MessageResolver;

import java.lang.reflect.Constructor;

/**
 * 异常工具类
 */
public class Exceptions {
    /**
     * 带国际化的异常可不传code
     *
     * @param msg
     * @param args
     */
    public static void msg(String msg, String... args) {
        throwEx(BaseException.class, msg, args);
    }


    /**
     * 不带国际化的异常
     *
     * @param msg
     */
    public static void base(String msg) {
        throw new BaseException(msg);
    }

    /**
     * 未找到异常
     *
     * @param msg
     */
    public static void notFound(String... msg) {
        throwEx(NotFoundException.class, "base.not.exists", msg);
    }


    public static void e(Exception e) {
        throw new BaseException(e);
    }


    /**
     * 抛出国际化异常和状态码
     *
     * @param clz
     * @param messageCode 配置对象code文件
     * @param args 用于传递格式化串占位符所用的运行期参数；
     * @throws RuntimeException
     */
    public static void throwEx(Class<? extends BaseException> clz, GlobalCodeEnum globalCodeEnum ,String... args) throws RuntimeException {
        BaseException throwable;
        try {
            String message = MessageResolver.getMessages(globalCodeEnum.getDesc(), (Object[]) args);
            Constructor<? extends BaseException> constructor = clz.getConstructor(String.class,Integer.class);
            //todo 状态码考虑从枚举中
            throwable = constructor.newInstance(message,globalCodeEnum.getCode());
        } catch (Exception e) {
            throwable = new BaseException(globalCodeEnum.getDesc());
        }
        throw throwable;
    }

    /**
     * 抛出国际化异常和状态码
     *
     * @param clz
     * @param messageCode 配置对象code文件
     * @param args 用于传递格式化串占位符所用的运行期参数；
     * @throws RuntimeException
     */
    public static void throwEx(Class<? extends BaseException> clz, String messageCode, String... args) throws RuntimeException {
        BaseException throwable;
        try {
            String message = MessageResolver.getMessages(messageCode, (Object[]) args);
            Constructor<? extends BaseException> constructor = clz.getConstructor(String.class,Integer.class);
            //todo 状态码考虑从枚举中
            throwable = constructor.newInstance(message,GlobalCodeEnum.GL_SUCC_0.getCode());
        } catch (Exception e) {
            throwable = new BaseException(messageCode);
        }
        throw throwable;
    }


}
